/**
 * @author [siwi]
 * @email [siwi@siwi.me]
 * @create date 2017-08-19 05:00:48
 * @modify date 2017-08-19 05:00:48
 * @desc [siwi logger 子进程日志输出到文件]
*/

const fs = require('fs')
const path = require('path')
const DateHelper = require('siwi-datehelper')
class Logger {
    constructor() {

    }

    /**
     *  初始化 创建日志目录
     * 
     * @param {string} [log_path=`${process.env.PWD}/log`] 
     */
    async init(config) {
        this.config = config
        if (!config) {
            console.log('缺少日志配置')
            return false
        }
        this.today = await DateHelper.date_format('yyyy-MM-dd')
        if (!fs.existsSync(config['path'])) {
            fs.mkdirSync(config['path'])
        }
        await this.getLogs()
    }

    /**
     * 打印日志
     * 
     * @param {any} msg 
     */
    async log(msg) {
        let run_time = await DateHelper.date_format("yyyy-MM-dd hh:mm:ss")
        let log_msg = `${run_time}:${this.config['name']}-output msg: ${msg}`

        /** 开发模式输出日志 **/
        if (process.env.NODE_ENV == 'dev') {
            console.log(log_msg)
        }
        let date = await DateHelper.date_format("yyyy-MM-dd")
        /** 判断是否过完一天 **/
        if (this.today === undefined || this.today !== date) {
            this.today = date
            this.writeStream && (this.writeStream.close(), delete this.writeStream)
        }
        /** 判断是否存在可写流 **/
        if (this.writeStream === undefined) {
            let log_file = `${this.config['path']}/${this.config['name']}-output-${date}.log`
            let options = {
                flags: 'a+',
                defaultEncoding: 'utf8',
                autoClose: true
            };
            this.writeStream = fs.createWriteStream(log_file, options)
        }
        
        /** 记录日志 **/
        this.writeStream.write(log_msg)

        /** 清除过期日志 **/
        await this.expire()
        return true
    }

    /* 获取日志  每日获取一次*/
    async getLogs() {
        let self = this
        let ttl = 24 * 60 * 60 * 1000;
        this.logs = fs.readdirSync(this.config['path'])
        setTimeout(() => {
            self.getLogs()
        }, ttl)
    }

    /* 删除过期日志 */
    async expire() {
        let time = Date.now() - this.config['expire'] * 1000
        let date = await DateHelper.date_format('yyyy-MM-dd', time)
        let file_name = `${this.config['name']}-output-${date}.log`
        let index = this.logs.indexOf(file_name)
        
        if (index !== -1) {
            let log_file = `${this.config['path']}/${file_name}`            
            if (fs.existsSync(log_file)) {
                fs.unlinkSync(log_file)
                this.logs.splice(index, 1);
            }
        }
    }
}

module.exports = new Logger()